<script setup lang="ts">
//@ts-nocheck
import {getCurrentInstance, nextTick, ref,Ref, watch} from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { 
  exists ,
  readDir
} from '@tauri-apps/plugin-fs';



const title=ref('Add Attack');
const emit=defineEmits(['add', 'edit'])
const ruleFormRef = ref<FormInstance>()
interface AttackItem {
    beginTime: number,
    name: string,
    id:number,//自动指定
    icon:string,
    delay:number,
    elements: AttackItem[]
}
interface Form {
    beginTime: number|'',
    name: string,
    icon:string,
    delay:number|""
}
const form:Ref<Form>=ref({
    beginTime: '',
    name: '',
    icon:'',
    delay:'',

})
const formAdd:Ref<Form>=ref({
    beginTime: '',
    name: '',
    icon:'',
    delay:'',

})
//@ts-ignore
const varifyNumber=(rule, value, callback) => {
    if (value === '') return callback();
    
    // 检查是否为有效数字
    const numValue = Number(value);
    if (Number.isNaN(numValue)) {
      return callback(new Error('请输入有效数字'));
    }
    
    // 检查小数位数
    if (value.includes('.')) {
      const decimalPart = value.split('.')[1];
      if (decimalPart.length > 2) {
        return callback(new Error('最多只能输入两位小数'));
      }
    }
    
    callback();
}
const rules = ref<FormRules<Form>>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' }
  ],
  beginTime: [{validator: varifyNumber,trigger: 'blur'}],
  delay: [
     { validator: varifyNumber, trigger: 'blur' }
  ],
  icon: [
    /* { required: true, message: 'Please select icon', trigger: 'change' } */
  ]
})


const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const handleClose=()=>{
    
    if (title.value==='Add Attack')formAdd.value={ ...form.value}
    else title.value='Add Attack'
    //console.log(formAdd.value)
}

const handleSubmit=async (formEl: FormInstance | undefined)=>{
    if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        
        const obj: AttackItem={
                beginTime:form.value.beginTime===''?-1:form.value.beginTime ,
                name: form.value.name,
                //@ts-ignore
                id:form.value.id||-1,
                icon:form.value.icon,
                delay:form.value.delay===''?-1:form.value.delay,
                //@ts-ignore
                elements: form.value.elements||[]
            }
        
        console.log('submit!',obj)
        if (title.value==='Add Attack')emit('add', obj)
        else emit('edit', obj)
        
      dialogFormVisible.value = false
      formEl.resetFields()
      
    } else {
      console.log('error submit!', fields)
    }
  })
}
const setTime=(obj:any)=>{
nextTick(()=>{
    formAdd.value.icon=''
    formAdd.value.name=''
    formAdd.value.beginTime=obj.beginTime
    formAdd.value.delay=obj.delay}
)
    
}
const setAll=(obj:any)=>{
  nextTick(()=>{
    form.value={...obj}
    if(form.value.delay!==-1)
    //@ts-ignore
    form.value.delay=String(form.value.delay)
    else{form.value.delay=''}
    if(form.value.beginTime!==-1)
    //@ts-ignore
    form.value.beginTime=String(form.value.beginTime)
    else{form.value.beginTime=''}
    //console.log(form.value)
  })
    
}
const handleOpen=()=>{
  ruleFormRef.value?.clearValidate();
  if (title.value==='Add Attack')form.value={ ...formAdd.value}
  //console.log(formAdd.value)
}
const selectProps={
  label: 'name',
  children:'children',
  isLeaf:'leaf',
  disabled:'disabled'
}
const rootLoad=ref({
  node:null,
  resolve:null,
  reject:null
})

const $globalProperties=getCurrentInstance()?.appContext.config.globalProperties;
const loadIcon=(node, resolve, reject )=>{//console.log(cacheData.value)
  //value可能使用简化版本

  if (node.level === 0) {
    rootLoad.value={node,resolve,reject}
    console.log(rootLoad.value)
    if ($globalProperties)readIconDirectory($globalProperties.$globalSetting.value.iconPath,'').then((res)=>{
    resolve(res)
  })
  }else{
    //console.log(node.data.directory)
    readIconDirectory(node.data.directory,node.data.path).then((res)=>{
      resolve(res)
    })
}
}
watch(()=>$globalProperties.$globalSetting.value.iconPath,async ()=>{
  form.value.icon=''
  formAdd.value.icon=''
if( rootLoad.value.node){
  rootLoad.value.node.childNodes=[]
  if ($globalProperties)readIconDirectory($globalProperties.$globalSetting.value.iconPath,'').then((res)=>{
    rootLoad.value.resolve(res)
  })
}
  
})

const readIconDirectory=async (directory:string,parent:string)=>{
   if (await exists(directory)) {
      const iconDirectory =directory;
      const iconFiles = await readDir(iconDirectory);
      const folders= iconFiles.filter(file=> file.isDirectory)
        .map(file=>{return{
          path:parent===''?`${file.name}`:parent+`/${file.name}`,
          directory:`${iconDirectory}/${file.name}`,
          value:-1,
          name:file.name,
          leaf:false
        }
      });
      const files=iconFiles.filter(file=> file.isFile && (file.name.includes('.png') || file.name.includes('.jpg') || file.name.includes('.jpeg'))).map(file=>{return{
        directory:`${iconDirectory}/${file.name}`,
        name:file.name,
        value:parent===''?  `${file.name}`:`${parent}/${file.name}`,
        leaf:true
        }
      });
      //console.log(iconFiles)
      const iconMap=[...folders,...files]
      if (iconMap.length>0) 
      //console.log(iconMap)
      return iconMap;
      else return[{
        directory:iconDirectory,
        name:'No icon',
        leaf:true,
        value:-1,
        disabled:true
      }]
    } else {
      return [{
        directory:'Path reading error',
        name:'Path reading error',
        leaf:true,
        value:-1,
        disabled:true
      }];
    }
}
/* const loadImage_select=(directory:any)=>{
  let url;
  loadImage(directory).then((res)=>{
    url= res
  })
  return url;
} */
/* const loadImage=async (directory:any)=>{
  try {
    const Data = await readFile(directory);
    // 创建Blob对象，用于显示图片
    const blob = new Blob([Data]);
    const Url = URL.createObjectURL(blob);
    return Url;
  } catch (error) {
    console.error('加载失败:', error);
    return null;
  }
} */
const imageSize=ref({width:'16px',height:'16px'})
defineExpose({
    dialogFormVisible,
    setTime,
    setAll,
    title
})
</script>

<template>
    <el-dialog v-model="dialogFormVisible" :title="title" width="500" @open="handleOpen" @closed="handleClose">
    <el-form :model="form" ref="ruleFormRef" :rules="rules">
      <el-form-item label="Attack name" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="icon (png/jpg/jpeg)" :label-width="formLabelWidth" prop="icon">
        <el-tree-select
          placeholder="Please select a icon"
          v-model="form.icon"
          lazy
          :load="loadIcon"
          :props="selectProps"
          :placement="'top'"
          clearable
        >
        <template #prefix>
          <ImgRender v-if="$globalProperties && form.icon" :url="$globalSetting.value.iconPath+'/'+form.icon" :size="imageSize"/>

        </template>
        <template #default="{ node, data }">
          <div style="display:inline-flex;align-items: center;">
          <ImgRender v-if="data.leaf && !data.disabled" :url="data.directory" :size="imageSize"/>
          <span style="margin-left: 5px;">{{ node.label }}</span>
          </div>
        </template>
        </el-tree-select>
      </el-form-item>
      <el-form-item label="Begin time (s)" :label-width="formLabelWidth" prop="beginTime" v-if="form.elements===undefined || form.elements.length<=0">
        <el-input v-model="form.beginTime" autocomplete="off" />
      </el-form-item>
      <el-form-item label="Delay (s)" :label-width="formLabelWidth" prop="delay" v-if="form.elements===undefined || form.elements.length<=0">
        <el-input v-model="form.delay" autocomplete="off" />
      </el-form-item>
      
    </el-form> 
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible= false">Cancel</el-button>
        <el-button type="primary" @click="handleSubmit(ruleFormRef)">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>


</style>